/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var marker;
var state;
var directionsDisplay;
var geocoder;
var map;
var userAddress;
var warehouses;
var directions;
var addressList=new Array();
function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(50.27, 30.30);
    var mapOptions = {
        zoom: 9,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);
    loadWarehouses();
}
            
                      
            
function calculate(){
    var minDistance;
    var minAddress;
    addressList = [];
    directions = [];
    console.log('START GOING THROUGH');
    for(var i=0;i<warehouses.length;i++) {
        var request = {
            origin: userAddress,
            destination: warehouses[i],
            travelMode: google.maps.TravelMode.DRIVING
        };
        var directionsService=new google.maps.DirectionsService();
        directionsService.route(request, function(result, status){
            if(status==google.maps.DirectionsStatus.OK){
                addressList.push(result.routes[0].legs[0].distance.value);
                directions.push(result);
                if(addressList.length === warehouses.length) {
                    // we've done everything, making work
                    console.log(addressList);
                    minDistance=addressList[0];
                    j=0;
                    for (var i=1;i<addressList.length;i++){
                        if(minDistance>addressList[i]){
                            minDistance=addressList[i];
                            j=i;
                        }
                    }
                    minAddress=warehouses[j];
                    minDirection=directions[j];
                    directionsDisplay.setDirections(minDirection);
                    var meters = minDistance % 1000;
                    var kilometers = ~~(minDistance/1000);
                    //console.log(minDistance, kilometers, meters);
                    $('#descr1').text('The nearest warehouse:');
                    $('#minAddress').text(minAddress);
                    $('#descr2').text('Route distance:');
                    $('#minDistance').text(kilometers+' km, '+meters+" m");
                }
            }
            else {
                $('#d1').text(status);
            }
        });
    }
    console.log('END GOING THROUGH');
                
}
            
function loadWarehouses(){
    $(document).ready(function() { 
        $.post('MapView',function(responseText) { 
            warehouses=$.parseJSON(responseText);
            codeWarehouses(warehouses);
        })        
    });
                
}
            
function codeWarehouses(list){
    $.each(list, function(index, value){
        code(value);
    })
}
            
function deleteMarker(temp){
    if(temp==1 && marker!=null){
        marker.setMap(null);
    }
}
function drawCustomMarker(){
    var pinColor = "#FE7569";
    var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));
    marker.setIcon("http://maps.google.com/mapfiles/ms/icons/yellow-dot.png");
    marker.setShadow(pinShadow);
}
            
function code(address,temp){
    geocoder.geocode({
        'address':address
    },function(results, status){
        state=status;
        deleteMarker(temp);
        if (status==google.maps.GeocoderStatus.OK){
            marker=new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            })
            if(temp!=1)
                marker=null;
            if(temp==1){
                drawCustomMarker();
            }
            map.setCenter(results[0].geometry.location);
        }
        else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    })
}

function codeUserAddress() {
    var address = document.getElementById("address").value;
    code(address,1);
    userAddress=address;
}

function drawRoute(){
    
}
            
google.maps.event.addDomListener(window, 'load', initialize);


